/****************************************************
          File Name:36-1.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sun 07 Sep 2014 03:06:56 PM CST
*****************************************************/

#define _GNU_SOURCE
#include<stdio.h>
#include<sched.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/time.h>
#include<sys/resource.h>

void err(char *fun)
{
    perror(fun);
    exit(errno);
}

void myput(char *status)
{
    FILE *fd;
    struct rusage use;

    getrusage(RUSAGE_CHILDREN,&use);

    if((fd=fopen("usage","a+"))==NULL)
        err("open");

    fprintf(fd,"%s:: %s %2ds; %s %2ds\n",status,"user CPU =",\
            use.ru_utime.tv_sec,"system CPU =",\
            use.ru_stime.tv_sec);

    fclose(fd);
}
int main(int argc,char *argv[])
{
    cpu_set_t set;
    int i,j;

    remove("usage");        // ignore error

    switch(fork())
    {
        case -1:
            err("fork");
            exit(1);
        case 0:
            CPU_ZERO(&set);
            CPU_SET(3,&set);
            if(sched_setaffinity(0,1,&set)==-1)
                err("sched_setaffinity");
            for(i=0;i<300000;i++)
                for(j=0;j<10000;j++)
                    ;
            break;
        default:
            myput("Before Wait");
            wait(NULL);
            myput("After Wait");
            break;
    }

    return 0;
}
